//
//  AlarmsTableViewController.m
//  iRMAP
//
//  Created by Ryan Enguero on 3/31/14.
//  Copyright (c) 2014 engueroryan. All rights reserved.
//

#import "AlarmsTableViewController.h"

#import "AlarmsCell.h"

#import "PostClass.h"

#import "ParserClass.h"

#import "Devices.h"

#import "ViewLogs.h"

#import "UiManager.h"

#import "loadingView.h"

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

@interface AlarmsTableViewController (){

    NSString *sessionIDStr;
    NSString *domainIDStr;
    NSString *deviceIDStr;
}

@end

@implementation AlarmsTableViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"View logs", @"View logs");
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
   // Devices *devices = [[ParserClass sharedItems] deviceDetails][0];
    
//    NSLog(@"View Logs = %@", [[PostClass sharedItems] getDevicesSessionID:sessionIDStr andDomainID:domainIDStr andDeviceID:0]);
//    
//    [[ParserClass sharedItems] viewLog:[[PostClass sharedItems] getDevicesSessionID:sessionIDStr andDomainID:domainIDStr andDeviceID:0]];
    
    UIImage *image = [UIImage imageNamed:@"MainMenu_Bg"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    UITableView *tableView = (UITableView*)self.view;
    tableView.backgroundView = imageView;
    [self.view setBackgroundColor:[UIColor clearColor]];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Esco_Banner_new"] forBarMetrics:UIBarMetricsDefault];
    
    [UiManager navigationHeaderWithTitle:@"Logs" andViewController:self];
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    [self.tblAlarms setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"loadingView" owner:self options:nil];
    loadingView * loading = [xib objectAtIndex:0];
    
    [loading setFrame:CGRectMake(0, -170, 93, 47)];
    
    [loading.imgLoading2 setAlpha:1.0];
    [loading.imgLoading setAlpha:0.0];
    
    //[loading.imgLoading setFrame:CGRectMake(0, 0, 193, 147)];
    
    UIView* bgLoading = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
    
    
    [bgLoading addSubview:loading];
    
    [self.tblAlarms setScrollEnabled:NO];

    [loading setBackgroundColor:[UIColor clearColor]];
    
    [self.view addSubview:bgLoading];

    dispatch_async(kBgQueue, ^{

        NSDictionary *json = [[PostClass sharedItems] getDevicesSessionID:sessionIDStr andDomainID:domainIDStr andDeviceID:0];
        
        if ([[[json objectForKey:@"response"] objectForKey:@"status"] isEqualToString:@"success"]) {
            
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [bgLoading removeFromSuperview];
            [self.tblAlarms setScrollEnabled:YES];
            [self.tblAlarms setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
            //  NSLog(@"View Logs = %@", [[PostClass sharedItems] getDevicesSessionID:sessionIDStr andDomainID:domainIDStr andDeviceID:0]);
            
            [[ParserClass sharedItems] viewLog:json];
            
            // [[ParserClass sharedItems] alarmLogs:[[PostClass sharedItems] getAlarmLog:sessionIDStr andDomainID:domainIDStr andDeviceID:deviceIDStr]];
            
            
            [self.tableView reloadData];

        
        
        });
        }else{
        
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [bgLoading removeFromSuperview];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@",[[[json objectForKey:@"response"] objectForKey:@"error"] objectForKey:@"code"]] message:[NSString stringWithFormat:@"%@",[[[json objectForKey:@"response"] objectForKey:@"error"] objectForKey:@"message"]] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            
            [alertView show];
            });
        
        }
    });
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [[[ParserClass sharedItems] viewLogsDetails] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
//    
//    // Configure the cell...
//    
//    return cell;
    
    
    
    
    static NSString *CellIdentifier = @"Cell";
    
    AlarmsCell *cell = (AlarmsCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AlarmsCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    // Configure the cell...
    
    ViewLogs *viewLogs = [[ParserClass sharedItems] viewLogsDetails][indexPath.row];
    
    cell.deviceCaption.text = [NSString stringWithFormat:@"%@ %@", [viewLogs voyagerTime], [viewLogs voyagerDate]];
    cell.errorTypeCaption.text = [viewLogs alarmText];
    //cell.deviceDescription.text = [viewLogs logDescription];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

#pragma mark - MainPageController Delegate 

-(void)getSessionID:(NSString *)seesionID andDomainID:(NSString *)domainID andDeviceID:(NSString *)deviceID{

    sessionIDStr = seesionID;
    domainIDStr = domainID;
    deviceIDStr = deviceID;
    

    NSLog(@"sessionID wewew = %@", seesionID);
}
@end
